package com.jfunit.java.helper;

import java.util.Map;
import java.util.Set;

import org.apache.commons.collections4.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfunit.java.util.ReflectionUtil;

/**
 * Bean助手类
 * 
 * @author Administrator
 *
 */
public final class BeanHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(BeanHelper.class);

    // 定义Bean映射，（用于存放Bean类与Bean实例的映射关系）,key : class value:对应的实例 也就是只能存在单例
    private static final Map<Class<?>, Object> BEAN_MAP = new HashedMap<Class<?>, Object>();

    static {
        System.out.println("======================================");
        System.out.println("BeanHelper-0,start:");
        Set<Class<?>> beanClassSet = ClassHelper.getBeanClassSet();
        System.out.println("BeanHelper-beanClassSet:"+beanClassSet);
        for (Class<?> beanClass : beanClassSet) {
            Object obj = ReflectionUtil.newInstance(beanClass);
            BEAN_MAP.put(beanClass, obj);
        }
        System.out.println("BeanHelper-BEAN_MAP:"+BEAN_MAP);
    }

    /**
     * 获取Bean映射
     * 
     * @return
     */
    public static Map<Class<?>, Object> getBeanMap() {
        return BEAN_MAP;
    }

    /**
     * 获取Bean实例
     * 
     * @param cls
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> cls){
        if (!BEAN_MAP.containsKey(cls)) {
            throw new RuntimeException("can not get bean by class:"+cls);
        }        
        return (T)BEAN_MAP.get(cls);
    }
    
    /**
     * 设置Bean实例
     * @param cls
     * @param obj
     */
    public static void setBean(Class<?> cls,Object obj){
        BEAN_MAP.put(cls, obj);
    }
}
